#include <iostream>
#include <cstring>
#include <string>

#include <sndfile.h>
#include "portaudio.h"

using namespace std;

class AudioObj{
    private:
        SF_INFO sfi;
        SNDFILE *sf;
        sf_count_t nread;
        size_t nframes;
        float *buf;
    public:
        AudioObj(string fileName){
            nframes = 512;
            memset(&sfi, 0, sizeof(sfi));
            sfi.samplerate = 44100;
            sfi.channels = 2;
            sfi.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;
            if ((sf = sf_open(fileName.c_str(), SFM_WRITE, &sfi)) == NULL){
                cout << "Could not open " << fileName << " with error NO." << sf_strerror(sf) << endl;
            }
            buf = new float[nframes * sfi.channels];
        }
        ~AudioObj(){
            sf_close(sf);
            delete buf;
        }
        void record(PaStream *stream){
            Pa_OpenDefaultStream(
                    &stream, 
                    sfi.channels, 
                    0, 
                    paFloat32, 
                    sfi.samplerate, 
                    paFramesPerBufferUnspecified, 
                    NULL, 
                    NULL);
            Pa_StartStream(stream);
            for(int i = 0; i != 200; i ++){
                Pa_ReadStream(stream, buf, nframes);
                sf_writef_float(sf, buf, nframes);
            }
            // while ((nread = sf_readf_float(sf, buf, nframes)) > 0)
            //     Pa_WriteStream(stream, buf, nread);
            Pa_StopStream(stream);
            Pa_CloseStream(stream);
        }
};
int main(int argc, char **argv)
{
    if (argc < 2){
        cout << "Syntax: " << argv[0] << " <filename>" << endl;
        return 1;
    }
    string Fname(argv[1]);
    AudioObj audio(Fname);
    PaStream *stream;
    Pa_Initialize();
    audio.record(stream);
    Pa_Terminate();
    return 0;
}
